/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum";
/* vue */
import { defineComponent } from "vue";
import { PropType } from "vue/types/v3-component-props";
/* scss */
import "@src/modules/setting/gpt/components/content.scss";
import { findComponentsDownward } from "@src/util/assist";
import { isFalsy } from "@src/util/type";

enum SettingGPTViewCheckboxGroupEventEnum {
  Change = 'change'
}

export default defineComponent({
  name: ComponentNameEnum.SettingGPTViewCheckboxGroup,
  props: {
    multiple: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    value: {
      type: Array as PropType<string[]>,
      default: () => []
    },
    onChange: {
      type: Function
    }
  },
  setup(props, { emit }) {
  },
  computed: {
  },
  watch: {
    value: {
      handler(newValue: string[]) {
        this.$nextTick(() => {
          this.valueChangeHandler(newValue)
        })
      },
      immediate: true
    }
  },
  methods: {
    emitChangeHandler(newValue: string[]) {
      this.$emit(SettingGPTViewCheckboxGroupEventEnum.Change, newValue)
    },
    onItemChangeHandler(checked: boolean, label: string) {
      
      // 单选
      if (isFalsy(this.multiple)) {
        const value = checked ? [label] : []
        this.emitChangeHandler(value)
        return
      }
      
      if (checked) {
        const value = [...this.value, label]
        this.emitChangeHandler(value)
        return
      }
      
      const value = this.value.filter((item: string) => item !== label)
      this.emitChangeHandler(value)
      
    },
    valueChangeHandler(newValue: string[]) {
      
      const checkboxComponents = findComponentsDownward(this, ComponentNameEnum.SettingGPTViewCheckbox)
      
      checkboxComponents.forEach((component: Record<string, any>) => {
        component.checked = newValue.includes(component.label)
      })
      
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.SettingGPTViewCheckboxGroup}>
        { this.$slots.default }
      </div>
    )
  }
});